import { Request, Response } from 'express';
import bcrypt from 'bcrypt';
const jwt = require('jsonwebtoken');
import { Op } from 'sequelize';
import { User } from '../models/User';
import { asyncHandler } from '../utils/asyncHandler';
import { AppError } from '../utils/errors';
import { formatSuccessResponse } from '../utils/response';
import config from '../config';
import logger from '../utils/logger';

export class AuthController {
  /**
   * 用户登录
   */
  login = asyncHandler(async (req: Request, res: Response) => {
    const { email, password, account, username, phone } = req.body;
    
    // 支持多种登录方式：邮箱、账号、用户名、手机号
    const loginField = email || account || username || phone;
    
    if (!loginField || !password) {
      throw new AppError('请提供登录凭据', 400);
    }

    // 查找用户（支持邮箱、用户名或手机号登录）
    const user = await User.findOne({
      where: {
        [Op.or]: [
          { email: loginField },
          { username: loginField },
          { phone: loginField }
        ]
      }
    });

    if (!user) {
      throw new AppError('用户不存在', 401);
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      throw new AppError('密码错误', 401);
    }

    // 检查用户状态
    if (user.status === 0) {
      throw new AppError('账户已被禁用', 401);
    }

    // 生成JWT token
        const payload = { 
          id: user.id, 
          username: user.username, 
          email: user.email 
        };
        const token = jwt.sign(payload, config.jwt.secret, { expiresIn: config.jwt.expiresIn });

    // 更新最后登录时间
    await user.update({ lastLoginAt: new Date() });

    // 返回用户信息（不包含密码）
    const userInfo = {
      userId: user.id,
      username: user.username,
      email: user.email,
      nickname: user.nickname,
      avatar: user.avatar,
      phone: user.phone,
      gender: user.gender,
      status: user.status,
      lastLoginAt: user.lastLoginAt
    };

    logger.info('用户登录成功', { userId: user.id, username: user.username });

    res.json(formatSuccessResponse('登录成功', {
      token,
      userInfo
    }));
  });

  /**
   * 用户注册
   */
  register = asyncHandler(async (req: Request, res: Response) => {
    const { username, email, password, phone, nickname } = req.body;

    // 基本验证
    if (!password) {
      throw new AppError('密码为必填项', 400);
    }

    if (!phone && !email) {
      throw new AppError('手机号或邮箱至少填写一项', 400);
    }

    if (password.length < 6) {
      throw new AppError('密码长度不能少于6位', 400);
    }

    // 验证手机号格式
    if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
      throw new AppError('手机号格式不正确', 400);
    }

    // 验证邮箱格式
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      throw new AppError('邮箱格式不正确', 400);
    }

    // 构建查询条件
    const whereConditions = [];
    if (username) whereConditions.push({ username });
    if (email) whereConditions.push({ email });
    if (phone) whereConditions.push({ phone });

    // 检查用户是否已存在
    if (whereConditions.length > 0) {
      const existingUser = await User.findOne({
        where: {
          [Op.or]: whereConditions
        }
      });

      if (existingUser) {
        if (existingUser.username === username) {
          throw new AppError('用户名已存在', 400);
        }
        if (existingUser.email === email) {
          throw new AppError('邮箱已被注册', 400);
        }
        if (existingUser.phone === phone) {
          throw new AppError('手机号已被注册', 400);
        }
      }
    }

    // 加密密码
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);

    // 生成默认用户名（如果没有提供）
    let finalUsername = username;
    if (!finalUsername) {
      if (phone) {
        finalUsername = `user${phone.slice(-4)}${Date.now().toString().slice(-6)}`;
      } else if (email) {
        const emailPrefix = email.split('@')[0].replace(/[^a-zA-Z0-9]/g, ''); // 移除非字母数字字符
        finalUsername = `user${emailPrefix}${Date.now().toString().slice(-6)}`;
      }
    }

    // 创建用户
    const user = await User.create({
      username: finalUsername,
      email: email || null,
      password: hashedPassword,
      phone: phone || null,
      nickname: nickname || finalUsername,
      status: 1
    });

    // 生成JWT token
    const token = jwt.sign(
      { 
        id: user.id, 
        username: user.username,
        email: user.email 
      },
      config.jwt.secret,
      { expiresIn: config.jwt.expiresIn }
    );

    // 返回用户信息（不包含密码）
    const userInfo = {
      userId: user.id,
      username: user.username,
      email: user.email,
      nickname: user.nickname,
      avatar: user.avatar,
      phone: user.phone,
      gender: user.gender,
      status: user.status
    };

    logger.info('用户注册成功', { userId: user.id, username: user.username });

    res.status(200).json(formatSuccessResponse('注册成功', {
      token,
      userInfo
    }));
  });

  /**
   * 获取当前用户信息
   */
  getProfile = asyncHandler(async (req: Request, res: Response) => {
    const userId = (req as any).user.userId;

    const user = await User.findByPk(userId, {
      attributes: { exclude: ['password'] }
    });

    if (!user) {
      throw new AppError('用户不存在', 404);
    }

    res.json(formatSuccessResponse('获取用户信息成功', user));
  });

  /**
   * 获取用户菜单（临时实现，后续可以从数据库获取）
   */
  getMenu = asyncHandler(async (req: Request, res: Response) => {
    // 临时的菜单数据，后续可以根据用户角色从数据库获取
    const menus = [
      {
        id: "/order",
        icon: "layui-icon-form",
        title: "订单管理",
        children: [
          {
            id: "/order/index",
            icon: "layui-icon-order",
            title: "订单管理"
          }
        ]
      },
      {
        id: "/user",
        icon: "layui-icon-username",
        title: "用户管理",
        children: [
          {
            id: "/user/index",
            icon: "layui-icon-user",
            title: "用户列表"
          },
          {
            id: "/user/address",
            icon: "layui-icon-location",
            title: "地址管理"
          }
        ]
      },
      {
        id: "/content",
        icon: "layui-icon-file",
        title: "内容管理",
        children: [
          {
            id: "/content/banner",
            icon: "layui-icon-picture",
            title: "轮播图管理"
          }
        ]
      },
      {
        id: "/product",
        icon: "layui-icon-component",
        title: "商品管理",
        children: [
          {
            id: "/product/goods",
            icon: "layui-icon-goods",
            title: "商品列表"
          },
          {
            id: "/product/category",
            icon: "layui-icon-tree",
            title: "商品分类"
          },
          {
            id: "/product/brand",
            icon: "layui-icon-diamond",
            title: "商品品牌"
          }
        ]
      }
    ];

    res.json(formatSuccessResponse('获取菜单成功', menus));
  });

  /**
   * 获取用户权限（临时实现，后续可以从数据库获取）
   */
  getPermissions = asyncHandler(async (req: Request, res: Response) => {
    // 临时的权限数据，后续可以根据用户角色从数据库获取
    const permissions = [
      'sys:user:add', 
      'sys:user:edit', 
      'sys:user:delete', 
      'sys:user:import', 
      'sys:user:export'
    ];

    res.json(formatSuccessResponse('获取权限成功', permissions));
  });
}